//
//  SSFotoBrowserViewController.swift
//  MyMicroBlog
//
//  Created by stevenSu on 15/8/8.
//  Copyright © 2015年 stevenSu. All rights reserved.
//

import UIKit
import SVProgressHUD

private let FotoCollectionViewID = "FotoCollectionViewID"
class SSFotoBrowserViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    var urls: [NSURL]
    var selectedIndex: Int
    
    init(url: [NSURL], index: Int) {
        self.urls = url
        selectedIndex = index
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        let path = NSIndexPath(forItem: selectedIndex, inSection: 0)
        fotoCollectionView.scrollToItemAtIndexPath(path, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
    }
    
    override func loadView() {
        super.loadView()
        var size = UIScreen.mainScreen().bounds.size
        size.width += 20
        view = UIView(frame: CGRect(origin: CGPointZero, size: size))
        
        setupUI()
        prepareLayout()
    }
    
    private func prepareLayout() {
        let layout = fotoCollectionView.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = view.bounds.size
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        fotoCollectionView.pagingEnabled = true
        fotoCollectionView.showsHorizontalScrollIndicator = false
    }
    
    private func setupUI() {
        view.addSubview(fotoCollectionView)
        view.addSubview(cancelButton)
        view.addSubview(saveButton)
        
        let dict = ["cv": fotoCollectionView, "cancelButton": cancelButton, "saveButton": saveButton]
        fotoCollectionView.translatesAutoresizingMaskIntoConstraints = false
        cancelButton.translatesAutoresizingMaskIntoConstraints = false
        saveButton.translatesAutoresizingMaskIntoConstraints = false
        // fotoCollectionView
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-(0)-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
//        fotoCollectionView.frame = view.bounds
        // cancelButton
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[cancelButton(32)]-10-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        // saveButton
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[saveButton(32)]-10-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-10-[cancelButton(100)]-(>=0)-[saveButton(100)]-30-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        
        fotoCollectionView.dataSource = self
        fotoCollectionView.registerClass(SSFotoBrowserCell.self, forCellWithReuseIdentifier: FotoCollectionViewID)
        cancelButton.addTarget(self, action: "cancelClicked", forControlEvents: UIControlEvents.TouchUpInside)
        saveButton.addTarget(self, action: "saveClicked", forControlEvents: UIControlEvents.TouchUpInside)
    }
    
    @objc private func cancelClicked() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func saveClicked() {
        let indexPath = fotoCollectionView.indexPathsForVisibleItems().last!
        let cell = fotoCollectionView.cellForItemAtIndexPath(indexPath) as! SSFotoBrowserCell
        guard let image = cell.imgView.image else {
            return
        }
        
        UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
    }
    
    func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject?) {
        if error != nil {
            print(error)
        }
        
        let message = (error == nil) ? "保存成功" : "保存失败"
        SVProgressHUD.showInfoWithStatus(message)
    }
    
    func getInteractionView() -> UIImageView {
        let indexPath = getIndexPath()
        let cell = fotoCollectionView.cellForItemAtIndexPath(indexPath) as! SSFotoBrowserCell
        return cell.imgView
    }
    
    func getIndexPath() -> NSIndexPath {
        return fotoCollectionView.indexPathsForVisibleItems().last!
    }
    
    private func hidden(hidden: Bool) {
        fotoCollectionView.backgroundColor = hidden ? UIColor.clearColor() : UIColor.blackColor()
        cancelButton.hidden = hidden
        saveButton.hidden = hidden
    }
    var scaleRatio: CGFloat = 1
    
    private lazy var fotoCollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout())
    
    private lazy var cancelButton: UIButton = UIButton(imgName: "none", backgroundImgName: "none", bgColor: UIColor.darkGrayColor(), fontColor: UIColor.whiteColor(), fontSize: 14, title: "取消")
    private lazy var saveButton: UIButton = UIButton(imgName: "none", backgroundImgName: "none", bgColor: UIColor.darkGrayColor(), fontColor: UIColor.whiteColor(), fontSize: 14, title: "保存")
}

extension SSFotoBrowserViewController: UICollectionViewDataSource, SSFotoBrowserCellDelegate {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return urls.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(FotoCollectionViewID, forIndexPath: indexPath) as! SSFotoBrowserCell
//        cell.backgroundColor = UIColor.blackColor()
        cell.imgURL = urls[indexPath.item]
        cell.fotoDelegate = self
        return cell
    }
    
    func fotoBrowserCellZoom(scale: CGFloat) {
        scaleRatio = scale
        hidden(scale < 1)
        if scale < 1 {
            startInteractiveTransition(self)
        } else {
            view.transform = CGAffineTransformIdentity
            view.alpha = 1.0
        }
    }
    
    func fotoBrowserCellEndZoom(cell: SSFotoBrowserCell, absoluteRect: CGRect) {
        if scaleRatio < 0.8 {
            
//            cell.imgView.frame = absoluteRect
//            print(cell.imgView.frame)
            completeTransition(true)
        } else {
            UIView.animateWithDuration(0.25, animations: { () -> Void in
                self.view.transform = CGAffineTransformIdentity
                self.view.alpha = 1.0
                }, completion: { (_) -> Void in
                    self.hidden(false)
                    self.scaleRatio = 1
            })
        }
    }
}

extension SSFotoBrowserViewController: UIViewControllerInteractiveTransitioning {
    func startInteractiveTransition(transitionContext: UIViewControllerContextTransitioning) {
        // TODO: maybe wrong
        view.transform = CGAffineTransformMakeScale(scaleRatio, scaleRatio)
        view.alpha = scaleRatio
    }
}

extension SSFotoBrowserViewController: UIViewControllerContextTransitioning {
    func containerView() -> UIView? {
        return view.superview
    }
    
    func isAnimated() -> Bool { return true }
    
    func isInteractive() -> Bool { return true }
    
    func transitionWasCancelled() -> Bool { return false }
    
    func presentationStyle() -> UIModalPresentationStyle { return UIModalPresentationStyle.Custom }

    func updateInteractiveTransition(percentComplete: CGFloat) {}
    func finishInteractiveTransition() {}
    func cancelInteractiveTransition() {}

    func completeTransition(didComplete: Bool) {
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @available(iOS 2.0, *)
    func viewControllerForKey(key: String) -> UIViewController? { return self }
    
    @available(iOS 8.0, *)
    func viewForKey(key: String) -> UIView? { return view }
    
    @available(iOS 8.0, *)
    func targetTransform() -> CGAffineTransform { return CGAffineTransformIdentity }

    @available(iOS 2.0, *)
    func initialFrameForViewController(vc: UIViewController) -> CGRect { return CGRectZero }
    @available(iOS 2.0, *)
    func finalFrameForViewController(vc: UIViewController) -> CGRect { return CGRectZero }
}
